package models

import (
	"OPS_TEMPLATE/util"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
	"time"
)

type Menu struct {
	Id          int       `pk;column(id);auto"`
	Code        string    `orm:"size(50); column(code)"`
	Description string    `orm:"size(50); column(description)"`
	CreateTime  time.Time `orm:"auto_now;type(datetime);column(createtime)"`
	Url         string    `orm:"size(50); column(url)"`
	Type        string    `orm:"size(50); column(type)"`
	Text        string    `orm:"size(50); column(text)"`
	// Img         string    `orm:"size(50); column(img)"`
	Mount  string `orm:"size(50); column(mount)"`
	Pid    int    `orm:"column(pid)"`
	Grade  int    `orm:"column(grade)"` //菜单级别
	Status string `orm:"column(status)"`
}

func (menu *Menu) GetAllmenus(grade int) (keyval []orm.Params) {
	sql := "SELECT * from menu WHERE grade=? and status='on'"
	GetOrm().Raw(sql, grade).Values(&keyval)
	return keyval
}

func (menu *Menu) Getleftmenus(id string) map[string][]orm.Params {
	var keyval, keyval1 []orm.Params
	maps := make(map[string][]orm.Params)
	sql := "SELECT * from menu WHERE pid=? and grade=2 and status='on' ORDER BY mount"
	GetOrm().Raw(sql, id).Values(&keyval)
	for _, m := range keyval {
		sql1 := "SELECT * from menu WHERE pid=? and grade=3 and status='on' ORDER BY mount"
		GetOrm().Raw(sql1, m["id"].(string)).Values(&keyval1)
		maps[m["text"].(string)] = keyval1
	}
	beego.Debug(maps)
	return maps
}

//验证
func (this *Menu) Valid() (res bool, errorm map[string]string) {
	errormap := make(map[string]string)
	var sql string
	var sql2 string
	bl := true
	if this.Id != 0 {
		sql = "SELECT * FROM menu WHERE text =\"" + this.Text + "\" and id <> " + strconv.Itoa(this.Id)
		sql2 = "SELECT * FROM menu WHERE Code =\"" + this.Code + "\" and id <> " + strconv.Itoa(this.Id)

	} else {
		sql = "SELECT * FROM menu WHERE text =\"" + this.Text + "\" "
		sql2 = "SELECT * FROM menu WHERE Code =\"" + this.Code + "\" "
	}
	o1 := GetOrm()
	var mm []Menu

	num, err := o1.Raw(sql).QueryRows(&mm)
	if err == nil {
		if num == 0 {
			bl = true
		} else {
			bl = false
			errormap["errText"] = "名字不能重复"
		}
	}

	num, err = o1.Raw(sql2).QueryRows(&mm)
	if err == nil {
		if num == 0 {
			bl = true

		} else {
			bl = false
			errormap["errCode"] = "编码不能重复"
		}
	}

	if strings.TrimSpace(this.Text) == "" {
		errormap["errText"] = "名字不能为空"
		bl = false
	}

	if strings.TrimSpace(this.Code) == "" {
		errormap["errCode"] = "编码不能为空"
		bl = false
	}

	if this.Grade == 3 && strings.TrimSpace(this.Url) == "" {
		errormap["errUrl"] = "Url不能为空"
		bl = false
	}

	if !util.IsNum(this.Mount) {
		errormap["errMount"] = "必须为数字"
		bl = false
	}

	return bl, errormap
}
